# coding: utf-8

import web
import datetime

import auth
import activity
import user
import discussion
import business
import feedback
from config import DB
from libs import NEED_LOGIN_URLS

urls = (
        '', auth.index,
        'index', auth.index,
        'login', auth.login,
        'logout', auth.logout,
        'signup', auth.signup,

        'map', user.map,
        'news', user.news,
        'profile', user.profile,
        'users', user.users,
        'avatar', user.avatar,
        'passwd', user.passwd,
        'setting', user.setting,

        'activity', activity.activity,
        'acts', activity.acts,
        'act_add', activity.add,
        'act_admin', activity.admin,
        'act_fakeuser', activity.fakeuser,

        'discuss_create', discussion.create,
        'discuss_show', discussion.show,
        'discuss_op', discussion.operation,

        'feedback', feedback.feedback,
        'feedback_reply', feedback.feedback_reply,

        'buy', business.buy,
        )

app_skate = web.application(urls, locals())


db = web.database(dbn=DB.server,
        db = DB.dbname,
        user = DB.username,
        pw = DB.password
        )

session = web.session.Session(
        app_skate, 
        web.session.DiskStore('sessions'),
        initializer={
            'user': 'anonymous',
            'id': -1,
            'super': False,
            'msg': None,
            'show_msg': False,
            }
        )

render = web.template.render(
        'templates/', base='layout', globals = {
            'context':session
            }
        )

def notfound():
    return web.notfound(render.notfound())

def need_login(path):
    for url in NEED_LOGIN_URLS:
        if url in path:
            return True
    return False

def login_require(handle):
    path = web.ctx.path
    web.ctx.username = name = session.user
    if name == 'anonymous' and need_login(path):
        session.show_msg = True
        session.msg = "请先登录"
        raise web.seeother('login')
    return handle()

def clean_session_msg(handle):
    if session.show_msg == True:
        session.show_msg = False
    else:
        session.msg = None
    return handle()

app_skate.notfound = notfound

app_skate.add_processor(login_require)
app_skate.add_processor(clean_session_msg)
